import React, {Component} from 'react';
import {Alert, Dimensions, Platform, StyleSheet, View} from 'react-native';
import Header from "../../components/header";
// 聊天的ui库
import IMUI from 'aurora-imui-react-native';
import JMessage from "../../utils/JMessage";
import {inject, observer} from "mobx-react";

// 文件操作库
let RNFS = require('react-native-fs');

// 聊天ui库输入组件
let InputView = IMUI.ChatInput;
// 消息展示列表
let MessageListView = IMUI.MessageList;
// 总的控制中心
const AuroraIController = IMUI.AuroraIMUIController;
// 获取屏幕相关的信息对象
const window = Dimensions.get('window');

let themsgid = 1;

// 负责创建各种类型的消息
function constructNormalMessage() {
  let message = {};
  message.msgId = themsgid.toString();
  themsgid += 1;
  // 消息的状态 => 发送完成
  message.status = "send_succeed";
  // 当前这条消息，是尕怂出去的，还是接受回来的，
  message.isOutgoing = true;
  message.timeString = '';
  message.fromUser = {
    userId: "",
    displayName: "",
    avatarPath: ""
  };

  return message
}

// 聊天页面
@inject('RootStore')
@observer
export default class TestRNIMUI extends Component {
  constructor(props) {
    super(props);
    let initHeight;
    if (Platform.OS === "ios") {
      initHeight = 46
    } else {
      initHeight = 100
    }
    this.state = {
      inputLayoutHeight: initHeight,
      messageListLayout: { flex: 1, width: window.width, margin: 0 },
      inputViewLayout: { width: window.width, height: initHeight, },
      isAllowPullToRefresh: true,
      navigationBar: {},
    }


    this.updateLayout = this.updateLayout.bind(this);
    this.onMsgClick = this.onMsgClick.bind(this);
    this.messageListDidLoadEvent = this.messageListDidLoadEvent.bind(this);
  }

  componentDidMount() {
    /**
     * Android only
     * Must set menu height once, the height should be equals with the soft keyboard height so that the widget won't flash.
     * 在别的界面计算一次软键盘的高度，然后初始化一次菜单栏高度，如果用户唤起了软键盘，则之后会自动计算高度。
     */
    if (Platform.OS === "android") {
      this.refs["ChatInput"].setMenuContainerHeight(316)
    }
    this.resetMenu()
    AuroraIController.addMessageListDidLoadListener(this.messageListDidLoadEvent);
  }

  messageListDidLoadEvent() {
    this.getHistoryMessage()
  }

  // 获取历史消息
  async getHistoryMessage() {
    // 获取极光的历史消息
    const history = await JMessage.getHistoryMessage('123123',1,1000);
    // 消息数组
    let messages = [];
    // console.log(history);
    history.forEach(item => {
      // 创建消息对象

      let message = constructNormalMessage();
      if(item.from.username === this.props.RootStore.userId){
        // 当前消息是属于发送者， 当前登录用户的
        message.isOutgoing = true;
        // 设置消息相关用户头像
        message.fromUser.avatarPath = 'https://www.itying.com/images/flutter/list1.jpg';
      } else {
        // 当前消息是属于接收者
        message.isOutgoing = false;
        message.fromUser.avatarPath = 'https://www.itying.com/images/flutter/list2.jpg';
      }

      if (item.type === 'text'){
        // 当前消息类型，图片还是文本
        message.msgType = 'text';
        // 设置消息内容
        message.text = item.text;
      } else if (item.type === 'image'){
        // 当前消息类型，图片还是文本
        message.msgType = 'image';
        // 设置消息内容
        message.mediaPath = item.thumbPath;
      }


      // 图片路径
      // message.mediaPath = '../../images/showfirend.png';

      // 发送时间
      message.timeString = (new Date(item.createTime)).toLocaleDateString();

      // 聊天消息的气泡大小
      message.contentSize = { 'height': 100, 'width': 200 };
      // 额外数据，暂时无用
      // message.extras = { "extras": "fdfsf" };
      messages.push(message)
    });

    //
    AuroraIController.appendMessages(messages);
    AuroraIController.scrollToBottom(true);
  }

  onInputViewSizeChange = (size) => {
    console.log("onInputViewSizeChange height: " + size.height + " width: " + size.width)
    if (this.state.inputLayoutHeight != size.height) {
      this.setState({
        inputLayoutHeight: size.height,
        inputViewLayout: { width: window.width, height: size.height },
        messageListLayout: { flex: 1, width: window.width, margin: 0 }
      })
    }
  };

  componentWillUnmount() {
    AuroraIController.removeMessageListDidLoadListener(this.messageListDidLoadEvent)
  }

  resetMenu() {
    if (Platform.OS === "android") {
      this.refs["ChatInput"].showMenu(false)
      this.setState({
        messageListLayout: { flex: 1, width: window.width, margin: 0 },
        navigationBar: { height: 64, justifyContent: 'center' },
      })
      this.forceUpdate();
    } else {
      AuroraIController.hidenFeatureView(true)
    }
  }

  /**
   * Android need this event to invoke onSizeChanged
   */
  onTouchEditText = () => {
    this.refs["ChatInput"].showMenu(false)
  }

  onFullScreen = () => {
    console.log("on full screen")
    this.setState({
      messageListLayout: { flex: 0, width: 0, height: 0 },
      inputViewLayout: { flex: 1, width: window.width, height: window.height },
      navigationBar: { height: 0 }
    })
  }

  onRecoverScreen = () => {
    // this.setState({
    //   inputLayoutHeight: 100,
    //   messageListLayout: { flex: 1, width: window.width, margin: 0 },
    //   inputViewLayout: { flex: 0, width: window.width, height: 100 },
    //   navigationBar: { height: 64, justifyContent: 'center' }
    // })
  }

  onAvatarClick = (message) => {
    Alert.alert()
    AuroraIController.removeMessage(message.msgId)
  }

  onMsgClick(message) {
    console.log(message)
    Alert.alert("message", JSON.stringify(message))
  }

  onMsgLongClick = (message) => {
    Alert.alert('message bubble on long press', 'message bubble on long press')
  }

  onStatusViewClick = (message) => {
    message.status = 'send_succeed'
    AuroraIController.updateMessage(message)
  }

  onBeginDragMessageList = () => {
    this.resetMenu()
    AuroraIController.hidenFeatureView(true)
  }

  onTouchMsgList = () => {
    AuroraIController.hidenFeatureView(true)
  }

  onPullToRefresh = () => {
    console.log("on pull to refresh")
    let messages = []
    for (let i = 0; i < 14; i++) {
      let message = constructNormalMessage()
      // if (index%2 == 0) {
      message.msgType = "text"
      message.text = "" + i
      // }

      if (i % 3 == 0) {
        message.msgType = "video"
        message.text = "" + i
        message.mediaPath = "/storage/emulated/0/ScreenRecorder/screenrecorder.20180323101705.mp4"
        message.duration = 12
      }
      messages.push(message)
    }
    AuroraIController.insertMessagesToTop(messages)
    if (Platform.OS === 'android') {
      this.refs["MessageList"].refreshComplete()
    }

  }

  // 发送文本信息
  onSendText = async (text) => {
    let message = constructNormalMessage();
    message.msgType = 'text';
    message.text = text;
    AuroraIController.appendMessages([message]);

    const username = '123123';
    const extras = {user: '123123'};
    let res = await JMessage.sendTextMessage(username, text, extras);
    console.log(res)
  };

  onTakePicture = (media) => {
    console.log("media " + JSON.stringify(media))
    let message = constructNormalMessage()
    message.msgType = 'image'
    message.mediaPath = media.mediaPath
    AuroraIController.appendMessages([message])
    this.resetMenu()
    AuroraIController.scrollToBottom(true)
  }

  onStartRecordVoice = (e) => {
    console.log("on start record voice")
  }

  onFinishRecordVoice = (mediaPath, duration) => {
    let message = constructNormalMessage()
    message.msgType = "voice"
    message.mediaPath = mediaPath
    message.timeString = "safsdfa"
    message.duration = duration
    AuroraIController.appendMessages([message])
    console.log("on finish record voice")
  }

  onCancelRecordVoice = () => {
    console.log("on cancel record voice")
  }

  onStartRecordVideo = () => {
    console.log("on start record video")
  }

  onFinishRecordVideo = (video) => {
    // let message = constructNormalMessage()

    // message.msgType = "video"
    message.mediaPath = video.mediaPath
    // message.duration = video.duration
    // AuroraIController.appendMessages([message])
  }

  // 发送图片消息
  onSendGalleryFiles = (mediaFiles) => {
    console.log(mediaFiles);
    mediaFiles.forEach(async item => {
      // 创建消息对象
      let message = constructNormalMessage();

      // 判断当前文件类型
      if (item.mediaType === "image") {
        message.msgType = "image";
      }

      message.mediaPath = item.mediaPath;

      // 设置消息状态 => 发送中
      message.status = "send_going";
      AuroraIController.appendMessages([message]);
      AuroraIController.scrollToBottom(true);

      const res = await JMessage.sendImageMessage('123123', item.mediaPath, {user: JSON.stringify(123123)})
      console.log(res);
      AuroraIController.updateMessage({...message, status:'send_succeed'});
    });

    this.resetMenu()
  };

  onSwitchToMicrophoneMode = () => {
    AuroraIController.scrollToBottom(true)
  }

  onSwitchToEmojiMode = () => {
    AuroraIController.scrollToBottom(true)
  }
  onSwitchToGalleryMode = () => {
    AuroraIController.scrollToBottom(true)
  }

  onSwitchToCameraMode = () => {
    AuroraIController.scrollToBottom(true)
  }

  onShowKeyboard = (keyboard_height) => {
  }

  updateLayout(layout) {
    this.setState({ inputViewLayout: layout })
  }

  onInitPress() {
    console.log('on click init push ');
    this.updateAction();
  }

  onClickSelectAlbum = () => {
    console.log("on click select album")
  }

  onCloseCamera = () => {
    console.log("On close camera event")
    this.setState({
      inputLayoutHeight: 100,
      messageListLayout: { flex: 1, width: window.width, margin: 0 },
      inputViewLayout: { flex: 0, width: window.width, height: 100 },
      navigationBar: { height: 64, justifyContent: 'center' }
    })
  }

  /**
   * Switch to record video mode or not
   */
  switchCameraMode = (isRecordVideoMode) => {
    console.log("Switching camera mode: isRecordVideoMode: " + isRecordVideoMode)
    // If record video mode, then set to full screen.
    if (isRecordVideoMode) {
      this.setState({
        messageListLayout: { flex: 0, width: 0, height: 0 },
        inputViewLayout: { flex: 1, width: window.width, height: window.height },
        navigationBar: { height: 0 }
      })
    }
  }

  render() {
    return (
      <View style={{flex: 1}}>
        <Header title={'聊天'} leftTitle={''} leftIcon={''}/>
        <View style={styles.container}>
          {/*聊天内容*/}
          <MessageListView style={this.state.messageListLayout}
                           ref="MessageList"
                           dateTextColor="#aaaaaa"
                           isAllowPullToRefresh={true}
                           onAvatarClick={this.onAvatarClick}
                           onMsgClick={this.onMsgClick}
                           onStatusViewClick={this.onStatusViewClick}
                           onTouchMsgList={this.onTouchMsgList}
                           onTapMessageCell={this.onTapMessageCell}
                           onBeginDragMessageList={this.onBeginDragMessageList}
                           onPullToRefresh={this.onPullToRefresh}
                           avatarSize={{ width: 50, height: 50 }}
                           avatarCornerRadius={25}
                           messageListBackgroundColor={"#f3f3f3"}
                           sendBubbleTextSize={18}
                           sendBubbleTextColor={"#000000"}
                           sendBubblePadding={{ left: 10, top: 10, right: 15, bottom: 10 }}
                           datePadding={{ left: 5, top: 5, right: 5, bottom: 5 }}
                           dateBackgroundColor={"#F3F3F3"}
                           photoMessageRadius={5}
                           maxBubbleWidth={0.7}
                           videoDurationTextColor={"#ffffff"}
          />

          {/*输入框*/}
          <InputView style={this.state.inputViewLayout}
                     ref="ChatInput"
                     onSendText={this.onSendText}
                     onTakePicture={this.onTakePicture}
                     onStartRecordVoice={this.onStartRecordVoice}
                     onFinishRecordVoice={this.onFinishRecordVoice}
                     onCancelRecordVoice={this.onCancelRecordVoice}
                     onStartRecordVideo={this.onStartRecordVideo}
                     onFinishRecordVideo={this.onFinishRecordVideo}
                     onSendGalleryFiles={this.onSendGalleryFiles}
                     onSwitchToEmojiMode={this.onSwitchToEmojiMode}
                     onSwitchToMicrophoneMode={this.onSwitchToMicrophoneMode}
                     onSwitchToGalleryMode={this.onSwitchToGalleryMode}
                     onSwitchToCameraMode={this.onSwitchToCameraMode}
                     onShowKeyboard={this.onShowKeyboard}
                     onTouchEditText={this.onTouchEditText}
                     onFullScreen={this.onFullScreen}
                     onRecoverScreen={this.onRecoverScreen}
                     onSizeChange={this.onInputViewSizeChange}
                     closeCamera={this.onCloseCamera}
                     switchCameraMode={this.switchCameraMode}
                     showSelectAlbumBtn={true}
                     showRecordVideoBtn={false}
                     onClickSelectAlbum={this.onClickSelectAlbum}
                     inputPadding={{ left: 30, top: 10, right: 10, bottom: 10 }}
                     galleryScale={0.6}//default = 0.5
                     compressionQuality={0.6}
                     cameraQuality={0.7}//default = 0.5
                     customLayoutItems={{
                       left: [],
                       right: ['send'],
                       bottom: ['voice','gallery','emoji','camera']
                     }}
          />
        </View>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  inputView: {
    backgroundColor: 'green',
    width: window.width,
    height: 100,
  },
});